package com.tarry.trade.counter.controller;

import com.tarry.trade.counter.cache.CacheType;
import com.tarry.trade.counter.cache.RedisStringCache;
import com.tarry.trade.counter.entity.*;
import com.tarry.trade.counter.service.UserService;
import com.tarry.trade.counter.thirdpart.uuid.MyUUID;
import com.tarry.trade.counter.util.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

@RestController
@RequestMapping("login")
@Slf4j
public class LoginController {

    @Resource
    private UserService userService;

    @GetMapping("/captcha")
    public ResultResp<CaptchaResp> captcha() {
        Captcha captcha = new Captcha(120, 40, 4, 10);
        String uuid = String.valueOf(MyUUID.getInstance().getUUID());
        RedisStringCache.cache(uuid, captcha.getCode(), CacheType.CAPTCHA);
        CaptchaResp captchaResp = CaptchaResp.builder().uuid(uuid).imageBase64(captcha.getImageBase64Str()).build();
        return ResultResp.success(captchaResp);
    }

    @PostMapping("userLogin")
    public ResultResp<Account> userLogin(@Valid LoginReq req) {
        log.debug("{}",req);
        Account account = userService.login(req.getUid(), req.getPassword(), req.getCaptcha(), req.getCaptchaId());
        return ResultResp.success(account);
    }

    @PostMapping("logOut")
    public ResultResp<String> loginOut(@Valid String token) {
        RedisStringCache.delete(token, CacheType.ACCOUNT);
        return ResultResp.success("退出成功！~");
    }

    @RequestMapping("loginFail")
    public ResultResp<String> loginFail(HttpServletRequest httpServletRequest) {
        String msg = (String) httpServletRequest.getAttribute("msg");
        if (StringUtils.isBlank(msg)){
            msg = "请重新登录~";
        }
        return ResultResp.error(msg);
    }
}
